import React, { useState } from 'react';
import { Input, Button, message, Spin, Typography, Image, Card } from 'antd';
import { UploadOutlined, SearchOutlined } from '@ant-design/icons';

const { Text } = Typography;

const DEFAULT_USER_ID = 'test_user_123';

const FunctionTestPanel: React.FC = () => {
  const [imageUrl, setImageUrl] = useState(''); // 本地可预览URL
  const [inputUrl, setInputUrl] = useState(''); // 用户输入的原始URL
  const [cleanUrl, setCleanUrl] = useState(''); // 清理后的原始URL，用于推理接口
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<string | null>(null);
  const [imgError, setImgError] = useState(false);
  const [imgLoading, setImgLoading] = useState(false);
  const [downloading, setDownloading] = useState(false); // 新增：下载中状态

  // 处理图片URL输入
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputUrl(e.target.value);
  };

  // 确认图片URL
  const handleConfirmUrl = async () => {
    if (!inputUrl) {
      message.warning('请输入图片URL');
      return;
    }
    // 自动清理输入URL
    const processedUrl = inputUrl.trim().replace(/^[@{]+|[}@]+$/g, '');
    setCleanUrl(processedUrl); // 保存清理后的URL用于推理
    setImgError(false);
    setImgLoading(true);
    setDownloading(true);
    setImageUrl('');
    setResult(null);
    try {
      const resp = await fetch('/api/download-image', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ image_url: processedUrl })
      });
      const data = await resp.json();
      if (resp.ok && data.local_url) {
        setImageUrl(data.local_url);
      } else {
        setImgError(true);
        message.error(data.error || '图片下载失败');
      }
    } catch (err: any) {
      setImgError(true);
      message.error('图片下载失败: ' + err.message);
    } finally {
      setDownloading(false);
    }
  };

  // 调用推理接口
  const handleCheckImage = async () => {
    if (!imageUrl) {
      message.warning('请先输入并确认图片URL');
      return;
    }
    
    if (!cleanUrl) {
      message.warning('请先确认图片URL');
      return;
    }
    
    setLoading(true);
    setResult(null);
    try {
      console.log('调用推理接口，使用原始URL:', cleanUrl);
      const resp = await fetch('http://118.145.200.164:5080/api/v1/check-image', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ image_url: cleanUrl, user_id: DEFAULT_USER_ID })
      });
      if (!resp.ok) throw new Error('接口请求失败');
      const data = await resp.json();
      setResult(JSON.stringify(data, null, 2));
    } catch (err: any) {
      setResult('推理失败: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <div style={{ marginBottom: 12 }}>
        <Input
          placeholder="请输入图片URL..."
          value={inputUrl}
          onChange={handleInputChange}
          onPressEnter={handleConfirmUrl}
          allowClear
          style={{ width: 'calc(100% - 90px)', marginRight: 8 }}
        />
        <Button icon={<SearchOutlined />} type="primary" onClick={handleConfirmUrl}>
          确认
        </Button>
      </div>
      {imageUrl && (
        <Card size="small" style={{ marginBottom: 12, textAlign: 'center' }}>
          {(imgLoading || downloading) && !imgError && <Spin style={{ margin: 16 }} />}
          <Image
            src={imageUrl}
            alt="预览图片"
            style={{ maxWidth: '100%', maxHeight: 200, objectFit: 'contain', display: imgError ? 'none' : undefined }}
            fallback=""
            preview={false}
            onLoad={() => { setImgLoading(false); setImgError(false); }}
            onError={() => { setImgLoading(false); setImgError(true); }}
          />
          {imgError && <div style={{ color: '#f5222d', marginTop: 8 }}>图片加载失败，请检查URL或图片跨域问题</div>}
          {cleanUrl && !imgError && (
            <div style={{ color: '#666', fontSize: '12px', marginTop: 8 }}>
              预览图片已就绪 | 推理将使用原始URL: {cleanUrl.length > 50 ? cleanUrl.substring(0, 50) + '...' : cleanUrl}
            </div>
          )}
        </Card>
      )}
      <Button
        type="primary"
        icon={<UploadOutlined />}
        onClick={handleCheckImage}
        loading={loading}
        block
        disabled={!imageUrl}
        style={{ marginBottom: 12 }}
      >
        推理检测
      </Button>
      <div style={{ minHeight: 80, background: '#fafbfc', borderRadius: 8, padding: 12, fontSize: 13 }}>
        <Text strong>命中结果：</Text>
        {loading ? <Spin size="small" /> : <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>{result || '（无）'}</pre>}
      </div>
    </div>
  );
};

export default FunctionTestPanel; 